import React, { useEffect, useState } from 'react';
import { StyleSheet, Text, ImageBackground, View, TouchableOpacity, TextInput, StatusBar } from 'react-native';
import { NavigationProp, RouteProp } from '@react-navigation/native';
import background from '../../assets/images/bacgroun_login.png';
import { CommonStyle } from '../../common/commonStyle.ts';
import Icon from 'react-native-vector-icons/Ionicons';
import AntDesign from 'react-native-vector-icons/AntDesign';
import { useToast } from 'react-native-toast-notifications';
import BouncyCheckbox from 'react-native-bouncy-checkbox/build/dist/BouncyCheckbox';
import Toast from 'react-native-toast-message';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import Tools from '../../utils/Tools.ts';
import { useBoolean, useReactive } from 'ahooks';
import StorageUtil from '../../utils/Storage.ts';
import to from '../../utils/to.ts';
import UserRequest from '../../request/userRequest.ts';
import Spinner from 'react-native-loading-spinner-overlay';
import userRequest from '../../request/userRequest.ts';
import { WX_APPID } from '../../common/config.ts';
import { useDispatch, useSelector } from 'react-redux';
import { AppDispatch, RootState } from '../../redux/store.ts';
import { fetchInitialUserInfo, removeShoppingCart, updateRegisterID } from '../../redux/reducers/app.ts';
import JPush from 'jpush-react-native';

interface ILoginScreenProps {
  navigation: NavigationProp<any, 'login'>;
  route: RouteProp<any, 'login'>;
}
const LoginScreen: React.FC<ILoginScreenProps> = ({ navigation, route }) => {
  const [check, setCheck] = useState<boolean>(false);
  const [phone, setPhone] = useState<string>('');
  const [loginType, setLoginType] = useState<number>(10); //1.账号密码, 10.验证码
  const loginUserState = useReactive({ account: '', password: '' });
  const [spinner, { toggle, setTrue, setFalse }] = useBoolean(false);
  const toast = useToast();
  const insets = useSafeAreaInsets();
  const registerID = useSelector((state: RootState) => state.registerID);
  const dispatch = useDispatch<AppDispatch>();

  useEffect(() => {
    // 获取registerID
    JPush.getRegistrationID((result) => {
      dispatch(updateRegisterID(result.registerID));
    });
  }, []);

  /**
   * 账号密码登录
   */
  const handleAccountLogin = () => {
    if (!check) {
      toast.show('请阅读并同意隐私协议', { placement: 'bottom' });
      return;
    }
    if (!loginUserState.account || !loginUserState.password) {
      toast.show('请输入账号密码', { placement: 'center' });
      return;
    }

    toggle();

    const loginParams = {
      userName: loginUserState.account,
      password: loginUserState.password,
      appId: WX_APPID,
      loginType,
      tenantId: '1510456530575347712',
      userRole: 2,
    };

    userRequest
      .Login(loginParams)
      .then(async (res) => {
        setFalse();
        const [tokenErr] = await to(StorageUtil.save<string>('token', res.data.userCode));
        const [userErr] = await to(StorageUtil.save<ILoginResponse>('userInfo', res.data));
        if (tokenErr || userErr) {
          Toast.show({ type: 'error', text1: '登录失败，请联系客服' });
          return;
        }
        dispatch(fetchInitialUserInfo());
        Toast.show({ type: 'success', text1: '登录成功 🎉' });
        dispatch(removeShoppingCart());
        navigation.navigate('tab');
      })
      .catch(() => {
        setFalse();
      });
  };

  /**
   * 获取验证码
   */
  const handleVerificationCode = () => {
    if (!check) {
      toast.show('请阅读并同意隐私协议', { placement: 'bottom' });
      return;
    }
    if (!phone || !Tools.isValidPhoneNumber(phone)) {
      toast.show('请输入手机号并保证手机号格式正确', { placement: 'bottom' });
      return;
    }
    if (!registerID) {
      toast.show('未能获取到registerID，请重启软件', { placement: 'bottom' });
      return;
    }

    toggle();
    UserRequest.FetchSMS({ mobile: phone, smsType: 101 })
      .then(() => {
        setFalse();
        Toast.show({ type: 'success', visibilityTime: 1000, text1: '发送验证码成功，请注意查看短信' });
        setTimeout(() => {
          navigation.navigate('checkSmsCaptchaScreen', { phone });
        }, 500);
      })
      .catch(() => {
        setFalse();
      });
  };

  /**
   * 渲染login视图
   */
  const renderLogin = () => {
    const styles = StyleSheet.create({
      root: { width: '100%', height: '100%', flexDirection: 'column', alignItems: 'flex-start', paddingHorizontal: 20 },
      phoneLoginTitle: { fontSize: 24, color: 'black', fontWeight: 'bold', marginTop: 54 },
      phoneLoginSubTitle: { fontSize: 12, color: CommonStyle.deepGrey, marginTop: 10 },
      passwordTip: { fontSize: 12, color: '#999', marginTop: 4 },
      phoneInputLayout: { width: '100%', height: 40, flexDirection: 'row', alignItems: 'center', borderBottomWidth: 0.5, borderBottomColor: '#ddd', marginTop: 15 },
      phoneInputPre: { fontSize: 16, color: 'black', fontWeight: 'bold' },
      phoneInputPreIcon: { width: 12, height: 6, marginLeft: 3 },
      phoneInput: { flex: 1, height: 50, backgroundColor: 'transparent', textAlign: 'left', textAlignVertical: 'center', fontSize: 19, fontWeight: 'bold', marginLeft: 10, color: '#333' },
      passwordInputLayout: { width: '100%', height: 40, flexDirection: 'row', alignItems: 'center', borderBottomWidth: 1, borderBottomColor: '#ddd', marginTop: 4 },
      passwordInput: { flex: 1, height: 40, backgroundColor: 'transparent', textAlign: 'left', textAlignVertical: 'center', fontSize: 16, marginRight: 16, color: '#333' },
      passwordEye: { width: 20, height: 20 },
      changeLayout: { width: '100%', marginTop: 10, alignItems: 'center', flexDirection: 'row' },
      exchangeIcon: { width: 12, height: 12 },
      codeLoginText: { fontSize: 11, color: CommonStyle.normalGrey, flex: 1, marginLeft: 4 },
      forgetPasswordText: {
        fontSize: 12,
        color: '#303080',
      },
      loginButton: { width: '100%', height: 38, backgroundColor: CommonStyle.mainColor, justifyContent: 'center', alignItems: 'center', borderRadius: 8, marginTop: 22 },
      loginText: { fontSize: 13, color: 'white', fontWeight: 'bold' },
    });

    const canLogin = check;

    return (
      <View style={[styles.root, { top: insets.top + 10 }]}>
        <View style={styles.root}>
          {/** 密码登录提示 */}
          <Text style={styles.phoneLoginTitle}>{loginType === 1 ? '账号密码登录' : '手机号登录'}</Text>

          {/** 登录手机号表单 */}
          <View style={styles.phoneInputLayout}>
            {loginType === 1 && <AntDesign size={20} name="user" />}
            {loginType === 10 && <Text style={styles.phoneInputPre}>+86</Text>}
            {/*<AntDesign style={styles.phoneInputPreIcon} name="close" />*/}

            {loginType === 1 && (
              <TextInput
                style={styles.phoneInput}
                placeholderTextColor="#999"
                placeholder="请输入账号"
                autoFocus={false}
                value={loginUserState.account}
                onChangeText={(text: string) => {
                  loginUserState.account = text;
                }}
              />
            )}
            {loginType === 10 && (
              <TextInput
                style={styles.phoneInput}
                placeholderTextColor="#999"
                placeholder="请输入手机号"
                autoFocus={false}
                keyboardType="number-pad"
                maxLength={13}
                value={phone}
                onChangeText={(text: string) => {
                  setPhone(text);
                }}
              />
            )}

            {phone && (
              <Icon
                color={CommonStyle.deepGrey}
                size={16}
                onPress={() => {
                  setPhone('');
                }}
                name="close-circle"
              />
            )}
            {loginUserState.account && (
              <Icon
                color={CommonStyle.deepGrey}
                size={16}
                onPress={() => {
                  loginUserState.account = '';
                }}
                name="close-circle"
              />
            )}
          </View>

          {loginType === 1 && (
            <View style={[styles.phoneInputLayout, { marginTop: 20 }]}>
              <AntDesign size={20} name="lock" />
              <TextInput
                style={styles.phoneInput}
                secureTextEntry={true}
                placeholderTextColor="#999"
                placeholder="请输入密码"
                autoFocus={false}
                value={loginUserState.password}
                onChangeText={(text: string) => {
                  loginUserState.password = text;
                }}
              />
              {loginUserState.password && (
                <Icon
                  color={CommonStyle.deepGrey}
                  size={16}
                  onPress={() => {
                    loginUserState.password = '';
                  }}
                  name="close-circle"
                />
              )}
            </View>
          )}

          {loginType === 1 ? (
            <View style={commonStyles.protocolLayout}>
              <TouchableOpacity onPress={() => setLoginType(2)}>
                <Text style={commonStyles.labelText}>手机号登录</Text>
              </TouchableOpacity>
            </View>
          ) : (
            <View style={commonStyles.protocolLayout}>
              <TouchableOpacity onPress={() => setLoginType(1)}>
                <Text style={commonStyles.labelText}>账号密码登录</Text>
              </TouchableOpacity>
            </View>
          )}

          {/** 登录 or 获取验证码按钮 */}
          {loginType === 1 && (
            <TouchableOpacity style={canLogin ? styles.loginButton : CommonStyle.unLoginButton} activeOpacity={canLogin ? 0.7 : 1} onPress={handleAccountLogin}>
              <Text style={styles.loginText}>{spinner ? '登录中...' : '登 录'}</Text>
            </TouchableOpacity>
          )}
          {loginType === 10 && (
            <TouchableOpacity style={canLogin ? styles.loginButton : CommonStyle.unLoginButton} activeOpacity={canLogin ? 0.7 : 1} onPress={handleVerificationCode}>
              <Text style={styles.loginText}>获取验证码</Text>
            </TouchableOpacity>
          )}

          {/** 注册登录协议 */}
          <View style={commonStyles.protocolLayout}>
            <TouchableOpacity>
              <BouncyCheckbox
                innerIconStyle={{ borderRadius: 0 }}
                iconStyle={{ borderRadius: 0 }}
                size={18}
                fillColor={CommonStyle.mainColor}
                unFillColor="#FFFFFF"
                onPress={() => {
                  setCheck(!check);
                }}
              />
            </TouchableOpacity>

            <Text style={commonStyles.labelText}>已阅读并同意</Text>
            <TouchableOpacity
              onPress={() => {
                navigation.navigate('userAgreement');
              }}
            >
              <Text style={commonStyles.protocolText}>软件许可及服务协议</Text>
            </TouchableOpacity>
            <Text style={[commonStyles.labelText, { marginLeft: 5 }]}>和</Text>
            <TouchableOpacity
              onPress={() => {
                navigation.navigate('privacyPolicy');
              }}
            >
              <Text style={commonStyles.protocolText}>隐私政策</Text>
            </TouchableOpacity>
          </View>
        </View>
      </View>
    );
  };

  return (
    <ImageBackground style={commonStyles.root} source={background}>
      <Spinner visible={spinner} textContent={'登录中...'} color={CommonStyle.mainColor} overlayColor={'rgba(0, 0, 0, 0.01)'} textStyle={CommonStyle.spinnerText} />
      {/** 隐藏状态栏 */}
      <StatusBar translucent backgroundColor={'transparent'} barStyle="dark-content" />
      {renderLogin()}
    </ImageBackground>
  );
};

const commonStyles = StyleSheet.create({
  root: { width: '100%', height: '100%', backgroundColor: 'white', flexDirection: 'column', alignItems: 'center' },
  protocolLayout: { width: '100%', flexDirection: 'row', alignItems: 'center', marginBottom: 10, marginTop: 15 },
  radioButton: { width: 20, height: 20 },
  labelText: { fontSize: 10, color: '#999', marginRight: 5 },
  protocolText: { fontSize: 10, color: CommonStyle.fontColor },
});

export default LoginScreen;
